package com.jack.leetcode.array;

public class 最接近的三数之和 {

    public static void main(String[] args) {
        int[] nums = {-1,2,1,-4};
        int target = 1;
        threeSumClosest(nums,target);
    }

    public static int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        int result = nums[0] + nums[1] + nums[2];
        int min = Math.abs(nums[0] + nums[1] + nums[2] - target);
        for (int i = 0; i < n - 2; i++) {
            for (int j = i + 1; j < n - 1; j++) {
                for (int k = j + 1; k < n; k++) {
                    int tmp = nums[i] + nums[j] + nums[k];
                    if (Math.abs(tmp - target) < Math.abs(min)) {
                        result = tmp;
                        min = Math.abs(tmp - target);
                    }
                }
            }
        }
        return result;
    }
}
